package com.agilerabbit.tools;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import android.R.integer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class AsynchImageLoader extends AsyncTask<String, integer, Bitmap> {

	ImageView pic = null;
	int pos;
	ViewHolder holder;
	ImageLruCacher cacher;

	public AsynchImageLoader(ViewHolder holder, ImageLruCacher cacher) {
		super();
		this.holder = holder;
		this.pic = holder.pic;
		this.pos = holder.position;
		this.cacher = cacher;
	}

	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	@Override
	protected Bitmap doInBackground(String... params) {

		Bitmap bitmap = null;
	
		lock.lock();
		try {

			String Url = params[0];
			bitmap = cacher.get(Url);
			
			if (bitmap == null) {

				if (BuildConfig.DEBUG)
					Log.d("AsychImageLoader", params[0]);

				bitmap = BitmapFactory.decodeStream((InputStream) new URL(
						params[0]).getContent());

				AddToCache(Url, bitmap);

				condition.signalAll();
			} else if (BuildConfig.DEBUG)
				Log.d("AsychImageLoader", "bitmap not null " + holder.position);

			return bitmap;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}

		return bitmap;
	}

	private void AddToCache(String url, Bitmap bitmap) {
		cacher.put(url, bitmap);
	}

	protected void onPostExecute(Bitmap bitmap) {
		if (bitmap != null && holder.position == pos) {

			if (holder.progressBar != null) {
				holder.pic.setVisibility(View.VISIBLE);
				holder.progressBar.setVisibility(View.GONE);
			}

			if (BuildConfig.DEBUG)
				Log.d("AsychImageLoader", Integer.toString(holder.position));
			pic.setImageBitmap(bitmap);
		}
	}

}
